package com.um.jdy.platform.order.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.um.jdy.baofu.api.BaoFuAccountService;
import com.um.jdy.baofu.api.BaofuPayService;
import com.um.jdy.baofu.entity.account.ContentBodyEntity;
import com.um.jdy.baofu.entity.account.RsultBodyEntity;
import com.um.jdy.baofu.entity.account.ValuesAcctInfoEntity;
import com.um.jdy.baofu.entity.account.ValuesActionEntity;
import com.um.jdy.baofu.utils.FormatUtil;
import com.um.jdy.common.baofu.entity.po.BaofuAccountDetails;
import com.um.jdy.common.baofu.entity.po.BaofuRefund;
import com.um.jdy.common.baofu.entity.po.BaofuUser;
import com.um.jdy.common.baofu.service.BaofuAccountDetailsService;
import com.um.jdy.common.baofu.service.BaofuRefundService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.charge.code.OrderCode;
import com.um.jdy.common.charge.entity.po.*;
import com.um.jdy.common.charge.entity.vo.*;
import com.um.jdy.common.charge.enums.OrderAction;
import com.um.jdy.common.charge.enums.OrderEnum;
import com.um.jdy.common.charge.enums.OrderStopReason;
import com.um.jdy.common.charge.service.*;
import com.um.jdy.common.commons.service.CommissionService;
import com.um.jdy.common.commons.service.StatusService;
import com.um.jdy.common.device.code.DeviceCode;
import com.um.jdy.common.device.entity.po.Pile;
import com.um.jdy.common.device.entity.po.Station;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.common.device.service.StationService;
import com.um.jdy.common.finance.entity.po.PlatformBill;
import com.um.jdy.common.finance.entity.po.UserBill;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.finance.service.MerchantBillService;
import com.um.jdy.common.finance.service.PlatformBillService;
import com.um.jdy.common.finance.service.PlatformProfitBillService;
import com.um.jdy.common.finance.service.UserBillService;
import com.um.jdy.common.member.entity.po.Wallet;
import com.um.jdy.common.member.enums.PayEnum;
import com.um.jdy.common.member.service.WalletService;
import com.um.jdy.common.platform.entity.po.RentSetting;
import com.um.jdy.common.platform.service.CompanyService;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.common.platform.service.RentSettingService;
import com.um.jdy.common.system.entity.po.Param;
import com.um.jdy.common.system.service.ParamService;
import com.um.jdy.common.commons.manager.WxManager;
import com.um.jdy.platform.order.entity.dto.OrderIdDTO;
import com.um.jdy.platform.order.entity.dto.OrderNoDTO;
import com.um.jdy.platform.order.entity.dto.RefundMoneyDTO;
import com.um.jdy.platform.order.entity.vo.*;
import com.um.jdy.platform.user.service.SessionUserService;
import com.um.jdy.rpc.enums.DeviceTypeEnum;
import com.um.jdy.rpc.factory.ServiceFactory;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.ExportParams;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.*;
import com.um.springcloud.dubbo.cluster.DeviceKey;
import com.um.weixin.pay.service.WxBasePayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Component
@Slf4j
public class ChargeOrderManager extends BaseManager<OrderService> {

    @Autowired
    SessionUserService sessionUserService;

    @Autowired
    CompanyService companyService;

    @Autowired
    StationService stationService;

    @Autowired
    PileService pileService;

    @Autowired
    WalletService walletService;

    @Autowired
    UserBillService userBillService;

    @Autowired
    MerchantBillService merchantBillService;

    @Autowired
    PlatformBillService platformBillService;

    @Autowired
    PlatformProfitBillService platformProfitBillService;

    @Autowired
    OrderCommissionService orderCommissionService;

    @Autowired
    EbOrderService ebOrderService;

    @Autowired
    EvOrderService evOrderService;

    @Autowired
    EboxOrderService eboxOrderService;

    @Autowired
    PbOrderService pbOrderService;

    @Autowired
    OrderPowerService orderPowerService;

    @Autowired
    DataLogService dataLogService;

    @Autowired
    MerchantService merchantService;

    @Autowired
    CommissionService calcCommission;

    @Autowired
    ServiceFactory serviceFactory;

    @Autowired
    ComplaintOrderService complaintOrderService;

    @Autowired
    WxManager wxManager;

    @Autowired
    WxBasePayService wxPayService;

    @Autowired
    DepositOrderService depositOrderService;

    @Autowired
    StatusService statusService;

    @Autowired
    RentSettingService rentSettingService;

    @Autowired
    OrderBillService orderBillService;

    @Autowired
    OrderFeeService orderFeeService;

    @Autowired
    OrderPlaceFeeService orderPlaceFeeService;

    @Autowired
    EvBmsPowerService bmsPowerService;

    @Autowired
    OrderEnergyService orderEnergyService;

    @Autowired
    OrderService orderService;

    @Autowired
    ParamService paramService;
    @Autowired
    BaofuPayService  baofuPayService;

    @Autowired
    BaofuRefundService baofuRefundService;

    @Autowired
    private BaofuAccountDetailsService baofuAccountDetailsService;

    @Autowired
    private BaoFuAccountService baoFuAccountService;

    /**
     * 分页查询订单
     *
     * @param pageParams
     * @return
     */
    public Response<Page<OrderItemVO>> page(PageParams pageParams) {
        Page<OrderItemVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());
        pageParams.getCondition().put("o.com_id", getComId());
        page = service.getCMSViewModelPageBySqlName(page, "get_charge_order_page", "get_charge_order_count",
                OrderItemVO.class, pageParams.getProperties(), pageParams.getValues(),
                pageParams.getRangeEntitys(), pageParams.getOrderNames(), pageParams.getSortOns());

        page.getResult().stream().forEach(orderItem -> {
            orderItem.setOrderStatus(statusService.getOrderStatus(orderItem.getChargeOrderId(),orderItem.getStatus(),orderItem.getPayStatus(),orderItem.getDeviceType()));

            if(orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing){
                service.setOrderDurationAndAmount(orderItem);

                if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EB.name())){
                    EbOrder ebOrder = ebOrderService.getEntity("charge_order_id", orderItem.getChargeOrderId());
                    if(ebOrder != null) {
                        if (orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing && StringUtil.equals(ebOrder.getFeeType(), OrderEnum.FeeType.Energy.name())) {
                            ebOrder.setServiceFee(orderService.getServiceFee(orderItem.getChargeOrderId()));
                            ebOrder.setEnergyFee(orderService.getEnergyFee(orderItem.getChargeOrderId()));

                            orderItem.setChargeAmount(ebOrder.getServiceFee() + ebOrder.getEnergyFee());
                            orderItem.setOrderAmount(orderItem.getChargeAmount());
                        }

                        if(orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing){
                            ebOrder.setChargeCapacity(orderService.getCapacity(orderItem.getChargeOrderId()));
                        }
                    }
                }
            }

            if(OrderEnum.OrderStatus.Place == orderItem.getOrderStatus() && DeviceTypeEnum.EV.name().equals(orderItem.getDeviceType())){
                EvOrderVO evOrderVO = UMBeanUtils.copyBean(evOrderService.getEntity("charge_order_id",orderItem.getChargeOrderId()),EvOrderVO.class);
                service.calcEVOrderPlaceFee(orderItem,evOrderVO);
            }else if(OrderEnum.OrderStatus.Place == orderItem.getOrderStatus() && DeviceTypeEnum.EBox.name().equals(orderItem.getDeviceType())){
                EboxOrderVO eboxOrderVO = UMBeanUtils.copyBean(eboxOrderService.getEntity("charge_order_id",orderItem.getChargeOrderId()),EboxOrderVO.class);
                service.calcEBoxOrderPlaceFee(orderItem,eboxOrderVO);
            }

            // TODO 订单列表免费订单不显示订单金额，订单详情要显示，后面可能会改
            if(YesOrNo.Yes.name().equals(orderItem.getIsFree())){
                orderItem.setOrderAmount(0);
            }
        });
        return Response.success(page);
    }

    /**
     * 投诉订单分页查询
     * @param pageParams
     * @return
     */
    public Response<Page<ComplaintOrderItemVO>> getComplaintPage(PageParams pageParams) {
        Page<ComplaintOrderItemVO> page = new Page<>();
        page.setPageNo(pageParams.getPageNo());
        page.setPageSize(pageParams.getPageSize());
        pageParams.getCondition().put("o.com_id", getComId());
        page = service.getCMSViewModelPageBySqlName(page, "get_charge_complaint_order_page", "get_charge_complaint_order_count",
                ComplaintOrderItemVO.class, pageParams.getProperties(), pageParams.getValues(),
                pageParams.getRangeEntitys(), pageParams.getOrderNames(), pageParams.getSortOns());

        page.getResult().stream().forEach(orderItem -> {
            orderItem.setOrderStatus(statusService.getOrderStatus(orderItem.getChargeOrderId(),orderItem.getStatus(),orderItem.getPayStatus(),orderItem.getDeviceType()));
        });
        return Response.success(page);
    }


    /**
     * 修改投诉订单状态
     * @param id
     * @param status
     * @return
     */
    public Response changeComplaintStatus(String id,String status){
        ComplaintOrder complaintOrder = complaintOrderService.getEntity(id);
        if(complaintOrder == null){
            Response.failed(DeviceCode.OrderNotExist);
        }
        complaintOrder.setUpdateUserId(sessionUserService.getTokenUserId());
        complaintOrder.setComplaintStatus(status);
        boolean result = complaintOrderService.update(complaintOrder);
        return result ? Response.success() : Response.failed();
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    public Response<OrderDetailVO> get(String id) {
        OrderDetailVO orderItemVO = service.getViewModel("get_charge_order_detail", OrderDetailVO.class,new Object[]{id});

        orderItemVO.setOrderStatus(statusService.getOrderStatus(orderItemVO.getChargeOrderId(),orderItemVO.getStatus(),orderItemVO.getPayStatus(),orderItemVO.getDeviceType()));

        switch (DeviceTypeEnum.valueOf(orderItemVO.getDeviceType())){
            case EB:
                EbOrder ebOrder = ebOrderService.getEntity("charge_order_id", orderItemVO.getChargeOrderId());
                if(ebOrder != null) {
                    if (orderItemVO.getOrderStatus() == OrderEnum.OrderStatus.Doing && StringUtil.equals(ebOrder.getFeeType(), OrderEnum.FeeType.Energy.name())) {
                        ebOrder.setServiceFee(orderService.getServiceFee(orderItemVO.getChargeOrderId()));
                        ebOrder.setEnergyFee(orderService.getEnergyFee(orderItemVO.getChargeOrderId()));

                        ebOrder.setChargeCapacity(orderService.getCapacity(orderItemVO.getChargeOrderId()));

                        orderItemVO.setChargeAmount(ebOrder.getServiceFee() + ebOrder.getEnergyFee());
                        orderItemVO.setOrderAmount(orderItemVO.getChargeAmount());
                    }

                    orderItemVO.setEbOrder(UMBeanUtils.copyBean(ebOrder,EbOrderVO.class));
                }
                break;
            case EV:
                EvOrder evOrder = (evOrderService.getEntity("charge_order_id",orderItemVO.getChargeOrderId()));
                if(evOrder != null)
                    orderItemVO.setEvOrder(UMBeanUtils.copyBean(evOrder,EvOrderVO.class));
                break;
            case EBox:
                EboxOrder eboxOrder = eboxOrderService.getEntity("charge_order_id",orderItemVO.getChargeOrderId());
                if(eboxOrder != null)
                    orderItemVO.setEboxOrder(UMBeanUtils.copyBean(eboxOrder,EboxOrderVO.class));
                break;
            case PB:
                PbOrderDetailVO pbOrderDetail = pbOrderService.getViewModel("get_pb_order_detail",PbOrderDetailVO.class,new Object[]{orderItemVO.getChargeOrderId()});
                if(pbOrderDetail != null)
                    orderItemVO.setPbOrder(pbOrderDetail);
                break;
        }

        if(orderItemVO.getOrderStatus() == OrderEnum.OrderStatus.Doing){
            if(orderItemVO.getDeviceType().equals(DeviceTypeEnum.EBox.name())){
                orderItemVO.setPayAmount(orderItemVO.getChargeAmount());
            }
        }else if(orderItemVO.getOrderStatus() == OrderEnum.OrderStatus.Place){
            if(orderItemVO.getDeviceType().equals(DeviceTypeEnum.EBox.name())){

                orderItemVO.getEboxOrder().setPlaceEndTime(new Date());
                service.calcEBoxOrderPlaceFee(orderItemVO,orderItemVO.getEboxOrder());

            } else if (orderItemVO.getDeviceType().equals(DeviceTypeEnum.EV.name())) {

                service.calcEVOrderPlaceFee(orderItemVO,orderItemVO.getEvOrder());

                // TODO 订单列表免费订单不显示订单金额，订单详情要显示，后面可能会改
                if(YesOrNo.Yes.name().equals(orderItemVO.getIsFree())){
                    orderItemVO.setOrderAmount(0);
                }
            }
        }

        ComplaintOrderDetailVO complaintOrder = complaintOrderService.getViewModel("get_complaint_order",ComplaintOrderDetailVO.class,
                new Object[]{orderItemVO.getChargeOrderId(),orderItemVO.getComId()});
        if(complaintOrder != null){
            complaintOrder.setComplaintThumbs(JSONUtil.parseJSONToList(StringUtil.getTrim(complaintOrder.getThumbs(),"[]")));
            orderItemVO.setComplaintOrder(complaintOrder);
        }

        return Response.success(orderItemVO);
    }

    /**
     * 充电订单退款失败，后台重新退款：暂不使用
     *
     * @param refundDTO
     * @return
     */
    public Response refund(OrderNoDTO refundDTO) {
        return null;
    }

    /**
     * 充电订单指定金额退款
     *
     * @param refundMoneyDTO
     * @return
     */
    @Transactional
    public Response refundMoney(RefundMoneyDTO refundMoneyDTO) {
        Order order = service.getEntity(new String[]{"order_no"}, new Object[]{refundMoneyDTO.getOrderNo()});
        if (order == null) {
            return Response.failed(OrderCode.NoOrder);
        }

        if (StringUtil.getTrim(order.getPayStatus()).equals(PayEnum.Status.UnPayed.name())) {
            return Response.failed(OrderCode.UnPayNotSupportReturn);
        }

        if ((StringUtil.toInt(order.getReturnAmount()) + refundMoneyDTO.getAmount()) > StringUtil.toInt(order.getPayAmount())) {
            return Response.failed(OrderCode.ReturnAmountLargeThanRefund);
        }

        String outTradeNo = StringUtil.getTrim(order.getOutTradeNo());
        String payPay = StringUtil.getTrim(order.getPayWay());

        //订单实际金额
        int orderAmount = StringUtil.toInt(order.getPayAmount()) - (StringUtil.toInt(order.getReturnAmount()) + refundMoneyDTO.getAmount());

        int returnAmount = refundMoneyDTO.getAmount();//本次退回金额
        boolean refundSuccess = true;//开发或测试环境，默认退款成功
        String returnMsg = "";
        String returnWay = payPay;//当是押金的情况下，则根据押金的支付方式来显示退回方式

        if (payPay.equals(PayEnum.PayWay.Wallet.name())) {//退回我的余额
            //记录钱包流水，金额为充值到账金额
            Wallet wallet = new Wallet();
            wallet.setMemberUserId(order.getMemberUserId());
            wallet.setNo(OrderUtil.getOrderNo());
            wallet.setOrderNo(refundMoneyDTO.getOrderNo());
            wallet.setAmount(refundMoneyDTO.getAmount());
            wallet.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
            wallet.setEvent(FinancialEnum.UserBillEvent.Refund.name());
            wallet.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
            wallet.setCreateTime(DateUtil.date());
            wallet.setRemark("后台管理员操作退款");
            walletService.save(wallet);

            //分账数据退回
            //宝付账户减值todo 只支持全部退款
            if(order.getIsBaofuSplit()==1 || order.getIsBaofuFireSplit() ==1){
                baofuRefund(order.getOutTradeNo());
            }

        } else if(payPay.equals(PayEnum.PayWay.Deposit.name()) && PayUtil.isProd()) {
            DepositOrder deposit = depositOrderService.getEntity("charge_order_id",order.getChargeOrderId());
            if(null == deposit){
                throw new ServiceException(OrderCode.NoDepositOrder);
            }

            outTradeNo = deposit.getOutTradeNo();
            returnWay = deposit.getPayWay();

            int totalFee = deposit.getAmount();
            int totalReturnAmount = returnAmount + deposit.getReturnAmount();//押金退款总金额

            if(totalReturnAmount > totalFee){
                throw new ServiceException(OrderCode.ReturnAmountLargeThanDeposit);
            }

            if(deposit.getPayWay().equals(PayEnum.PayWay.Wxpay.name())) {//微信支付
                /** todo 修改成宝付退款
                try {
                    wxManager.getPayService(order.getComId());
                    wxPayService.refundOrder(outTradeNo, OrderUtil.getWxOrderNo(), totalFee, returnAmount);

                    deposit.setPayOrderAmount(totalFee - totalReturnAmount);
                    deposit.setReturnAmount(totalReturnAmount);
                    deposit.setReturnStatus(OrderEnum.DepositReturnStatus.Yes.name());
                    deposit.setReturnTime(new Date());
                    depositOrderService.update(deposit);

                } catch (WxPayException ex) {
                    returnMsg = ex.getCustomErrorMsg();
                    refundSuccess = false;
                }*/
                BaofuRefund baofuRefund = new BaofuRefund();
                try {
                    String type ="chargeEb";
                    String refundNo = OrderUtil.getWxOrderNo();
                    baofuPayService.refundOrder(outTradeNo, refundNo, totalFee, returnAmount,type,order.getComId());
                    deposit.setPayOrderAmount(totalFee - totalReturnAmount);
                    deposit.setReturnAmount(totalReturnAmount);
//                    deposit.setReturnStatus(OrderEnum.DepositReturnStatus.Yes.name());
//                    deposit.setReturnTime(new Date());
                    depositOrderService.update(deposit);


                    baofuRefund.setComId(order.getComId());
                    baofuRefund.setRefundAmount(returnAmount);
                    baofuRefund.setOutRefundNo(refundNo);
                    baofuRefund.setRefundState("REFUND");
                    baofuRefund.setOutTradeNo(outTradeNo);
                    baofuRefund.setType(type);


                    order.setReturnAmount(StringUtil.toInt(order.getReturnAmount()) + returnAmount);//已退金额+本次退款金额
                    order.setOrderAmount(orderAmount);
                    order.setReturnStatus(OrderEnum.ReturnStatus.Refund.name());
                    order.setReturnWay(returnWay);
                    order.setReturnTime(new Date());
                    service.save(order);

                    return Response.success("宝付退款中");
                } catch (ServiceException ex) {

                    returnMsg = ex.getMsg();
                    refundSuccess = false;
                    baofuRefund.setRefundState("ABNORMAL");
                    baofuRefund.setErrMsg(returnMsg);
                    log.info("宝付指定退款失败！"+ex.getMsg());
                    return Response.success("宝付退款中");
                }finally {
                    baofuRefundService.addRefund(baofuRefund);
                }
            }else if (deposit.getPayWay().equals(PayEnum.PayWay.Alipay.name())) {//支付宝支付
                // TODO: 2023-06-13 支付宝退款
            }

        } else if(payPay.equals(PayEnum.PayWay.Wxpay.name()) && PayUtil.isProd()) {//微信支付
            /**
            try {
                wxManager.getPayService(order.getComId());
                int totalFee = StringUtil.toInt(order.getPayAmount());//微信充电的订单金额
                wxPayService.refundOrder(outTradeNo, OrderUtil.getWxOrderNo(), totalFee, returnAmount);
            }catch (WxPayException ex){
                returnMsg = ex.getCustomErrorMsg();
                refundSuccess = false;
            }*/
            BaofuRefund baofuRefund = new BaofuRefund();
            try {
                String type ="chargeEb";
                String refundNo = OrderUtil.getWxOrderNo();
                int totalFee = StringUtil.toInt(order.getPayAmount());//微信充电的订单金额

                baofuPayService.refundOrder(outTradeNo, refundNo, totalFee, returnAmount,type,order.getComId());


                baofuRefund.setComId(order.getComId());
                baofuRefund.setRefundAmount(returnAmount);
                baofuRefund.setOutRefundNo(refundNo);
                baofuRefund.setRefundState("REFUND");
                baofuRefund.setOutTradeNo(outTradeNo);
                baofuRefund.setType(type);

                order.setReturnStatus(OrderEnum.ReturnStatus.Refund.name());
                order.setReturnAmount(StringUtil.toInt(order.getReturnAmount()) + returnAmount);//已退金额+本次退款金额
                order.setOrderAmount(orderAmount);
                order.setReturnWay(returnWay);
                order.setReturnTime(new Date());
                service.save(order);

                return Response.success("宝付退款中");
            } catch (ServiceException ex) {
                returnMsg = ex.getMsg();
                refundSuccess = false;
                baofuRefund.setRefundState("ABNORMAL");
                baofuRefund.setErrMsg(returnMsg);
                log.info("宝付指定退款失败！"+ex.getMsg());
                return Response.success("宝付退款中");
            }finally {
                baofuRefundService.addRefund(baofuRefund);
            }

        }else if (payPay.equals(PayEnum.PayWay.Alipay.name()) && PayUtil.isProd()) {//支付宝支付
                // TODO: 2023-06-13 支付宝退款
                //                    Map refundResult = new HashMap();
                //                    try {
                //                        refundResult = payService.refund(outTradeNo, payUtil.toDoubleAmount(returnAmount));
                //                        log.info("支付宝退款返回:" + JSONUtil.toJSONString(refundResult));
                //                        refundSuccess = true;
                //                    } catch (Exception e) {
                //                        returnMsg = StringUtil.getTrim(refundResult.get("sub_msg"));
                //                    }
        }


        if (refundSuccess) {
            //order.setChargeAmount(chargeAmount); 不需要改变金额
            order.setReturnAmount(StringUtil.toInt(order.getReturnAmount()) + returnAmount);//已退金额+本次退款金额
            order.setOrderAmount(orderAmount);
            order.setReturnStatus(OrderEnum.ReturnStatus.Success.name());
            order.setReturnWay(returnWay);
            order.setReturnTime(new Date());
            service.save(order);

            //记录账户流水，金额为支付金额
            if(!payPay.equals(PayEnum.PayWay.Wallet.name())) {//不是钱包支付，才需要记录平台收支流水和会员收支流水
                addRefundWechatOrAlipayBill(StringUtil.getTrim(order.getMemberUserId()), refundMoneyDTO.getOrderNo(), outTradeNo, returnAmount);
            }

        } else {
            return Response.failed("退款失败：" + returnMsg);
        }

        String chargeOrderId = StringUtil.getTrim(order.getChargeOrderId());
        Station station = stationService.getEntity(order.getDeviceStationId());
        if (station == null) {
            throw new ServiceException(DeviceCode.NoStation);
        }

        // 校验是否进行分佣
        if (this.checkCommission(order)) {

            //充电宝成本。买断或超时长，充电宝不归还，分佣金额需减掉成本
            /*if(DeviceTypeEnum.PB.getKey().equals(order.getDeviceType())){
                PbOrder pbOrder = pbOrderService.getRow("charge_order_id", order.getChargeOrderId());
                if(null != pbOrder && (YesOrNo.Yes.name().equals(pbOrder.getIsBuy()) ||
                        YesOrNo.Yes.name().equals(pbOrder.getIsTimeout()))){
                    RentSetting rentSetting = rentSettingService.getRow("com_id", order.getComId());
                    orderAmount -= (null == rentSetting ? 0 : rentSetting.getPowerPrice() * 100);
                }
            }*/

            int profit = calcCommission.refundCommission(chargeOrderId,new Date(), refundMoneyDTO.getOrderNo(), outTradeNo, returnAmount,orderAmount);
            order.setProfit(order.getProfit() - profit);
        }

        service.save(order);

        return Response.success();
    }

    /**
     * 退款：记录平台收支流水和用户收支流水
     * @param userId 用户id
     * @param orderNo 订单ID
     * @param outTradeNo 交易号
     * @param returnAmount 本次退款金额
     */
    private void addRefundWechatOrAlipayBill(String userId, String orderNo, String outTradeNo, int returnAmount) {

        //充电退回
        UserBill userBill = new UserBill();
        userBill.setMemberUserId(userId);
        userBill.setNo(OrderUtil.getOrderNo());
        userBill.setOutTradeNo(outTradeNo);
        userBill.setOrderNo(orderNo);
        userBill.setAmount(returnAmount);
        userBill.setType(FinancialEnum.IncomeOrExpend.Income.name());//收入支出类型：0-收入，1-支出
        userBill.setEvent(FinancialEnum.UserBillEvent.Refund.name());
        userBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
        userBill.setCreateTime(DateUtil.date());
        userBill.setRemark("后台管理员操作退款");
        userBillService.save(userBill);

        //插入平台账单流水：充电退回
        PlatformBill platformBill = new PlatformBill();
        platformBill.setNo(OrderUtil.getOrderNo());
        platformBill.setOutTradeNo(outTradeNo);
        platformBill.setOrderNo(orderNo);
        platformBill.setAmount(returnAmount);
        platformBill.setType(FinancialEnum.IncomeOrExpend.Expend.name());//收入支出类型：0-收入，1-支出
        platformBill.setEvent(FinancialEnum.PlatformBillEvent.OrderRefund.name());
        platformBill.setStatus(FinancialEnum.BillStatus.Effective.name());//账单状态：0未生效|1已生效|2已失效
        platformBill.setCreateTime(DateUtil.date());
        platformBill.setRemark("后台管理员操作退款");
        platformBillService.save(platformBill);
    }

    /**
     * 校验是否进行分佣：白名单/被扣押订单/未设置结算订单，都不进行分佣
     *
     * @param order
     * @return
     */
    private boolean checkCommission(Order order) {
        //是否是免费订单
        if (isFreeOrder(order)) {
            return false;
        }
        return true;
    }

    /**
     * 是否是免费充电订单
     *
     * @param order
     * @return
     */
    private boolean isFreeOrder(Order order) {
        return YesOrNo.Yes.name().equals(StringUtil.getTrim(order.getIsFree()));
    }

    /**
     * 停止充电
     *
     * @param orderNoDTO
     * @return
     */
    public Response stop(OrderNoDTO orderNoDTO) {
        Order order = service.getEntity(new String[]{"order_no"}, new Object[]{orderNoDTO.getOrderNo()});
        if (order == null) {
            return Response.failed(OrderCode.NoOrder);
        }

        Pile pile = pileService.getEntity(order.getDevicePileId());
        if (pile == null) {
            return Response.failed(DeviceCode.NoDevice);
        }

        String deviceName = StringUtil.getTrim(pile.getIccid());
        // 设备离线
        if (!DeviceEnum.DeviceStatus.Online.name().equals(pile.getDeviceStatus())) {
            return Response.failed(DeviceCode.DeviceOffline);
        }

        // 订单记录sysEndType
        Order order1 = new Order();
        order1.setChargeOrderId(order.getChargeOrderId());
        order1.setEndType(OrderStopReason.EB.ADMIN_END.name());
        service.update(order1);

        saveChargeData(order.getComId(),order.getChargeOrderId(),OrderAction.EB.AdminStopChargeReq,new Date(),new Object(),"后台管理员结束订单");
        try {
            if (DeviceTypeEnum.EB.getKey().equals(pile.getDeviceType())) {
                serviceFactory.getRpcEBDeviceService(pile.getProtocol()).reqStopCharge(order.getOrderNo(), new DeviceKey(pile.getImei()), order.getPort());
            }else if (DeviceTypeEnum.EV.getKey().equals(pile.getDeviceType())) {
                serviceFactory.getRpcEVDeviceService(pile.getProtocol()).stopCharge(new DeviceKey(pile.getImei()), order.getPort());
            }else if (DeviceTypeEnum.EBox.getKey().equals(pile.getDeviceType())) {
                serviceFactory.getRpcEBoxDeviceService(pile.getProtocol()).reqStopCharge(order.getOrderNo(), new DeviceKey(pile.getImei()), order.getPort());
            }else if (DeviceTypeEnum.PB.getKey().equals(pile.getDeviceType())) {
                // TODO: 2023-06-23
            }
        } catch (Exception ex) {
            log.error("停止订单失败：{}",ex.getMessage());
            return Response.failed(OrderCode.RemoteStopFailure);
        }

        return Response.success();
    }

    /**
     * 订单日志
     *
     * @param orderIdDTO
     * @return
     */
    public Response<List<DataLog>> getLogs(OrderIdDTO orderIdDTO) {
        List<DataLog> logs = dataLogService.getList(new String[]{"charge_order_id"}, new Object[]{orderIdDTO.getChargeOrderId()},
                new String[]{"auto_id"}, new String[]{"asc"});
        return Response.success(logs);
    }

    /**
     * 查询订单实时功率
     * @param orderIdDTO
     * @return
     */
    public Response<List<OrderPower>> getOrderPowers(OrderIdDTO orderIdDTO) {
        List<OrderPower> powers = orderPowerService.getList(new String[]{"charge_order_id"}, new Object[]{orderIdDTO.getChargeOrderId()},
                new String[]{"create_time"}, new String[]{"asc"});
        return Response.success(powers);
    }

    /**
     * 处理异常订单
     * @param list
     * @return
     */
    @Transactional
    public Response handleExceptionOrder(List<String> list){
        for(String id : list){
            Order order = new Order();
            order.setChargeOrderId(id);
            order.setExceptionStatus(YesOrNo.Yes.name());
            service.update(order);
        }

        return Response.success();
    }

    /**
     * 投诉订单标为已处理
     * @param list
     * @return
     */
    @Transactional
    public Response handleComplaintOrder(List<String> list){
        for(String id : list){
            ComplaintOrder order = complaintOrderService.getEntity(id);
            if(order != null) {
                order.setComplaintStatus(YesOrNo.Yes.name());
                order.setUpdateUserId(sessionUserService.getTokenUserId());
                complaintOrderService.update(order);
            }
        }

        return Response.success();
    }

    public OrderBillVO getOrderBill(String chargeOrderId){
        OrderBill entity = orderBillService.getEntity("charge_order_id", chargeOrderId);
        return BeanUtil.toBean(entity, OrderBillVO.class);
    }

    public List<OrderFeeVO> getOrderFee(String chargeOrderId){
        List<OrderFee> list = orderFeeService.getList("charge_order_id", chargeOrderId, "start_time", "asc");
        return BeanUtil.copyToList(list, OrderFeeVO.class);
    }

    public List<OrderPlaceFeeVO> getOrderPlaceFee(String chargeOrderId){
        List<OrderPlaceFee> list = orderPlaceFeeService.getList("charge_order_id", chargeOrderId, "place_start_time", "asc");
        return BeanUtil.copyToList(list, OrderPlaceFeeVO.class);
    }

    /**
     * 保存记录订单操作日志
     * @param orderId 订单ID
     * @param action 操作类型
     * @param time 时间
     * @param data 其他数据
     * @param remark 描述
     */
    public void saveChargeData(String comId, String orderId, OrderAction.EB action, Date time, Object data, String remark){
        DataLog dataLog = new DataLog();
        dataLog.setComId(comId);
        dataLog.setChargeOrderId(orderId);
        dataLog.setAction(action.name());
        dataLog.setActionZh(action.getValue());
        dataLog.setCreateTime(time);
        dataLog.setJsonData(cn.hutool.json.JSONUtil.toJsonStr(data));
        dataLog.setRemark(remark);
        dataLogService.saveRow(dataLog);
    }

    public List<EvBmsPowerVO> getBmsPower(String chargeOrderId){
        List<EvBmsPower> list = bmsPowerService.getList("charge_order_id", chargeOrderId, "create_time", "asc");
        return BeanUtil.copyToList(list, EvBmsPowerVO.class);
    }


    public List<OrderEnergyItem> getOrderFeeList(String chargeOrderId){
        EbOrder ebOrder = ebOrderService.getEntity("charge_order_id",chargeOrderId);
        if(ebOrder != null) {
            return orderService.getOrderFeeList(chargeOrderId);
        }else{
            return new ArrayList<>();
        }
    }

    public Response exportOrderPage(ExportParams exportParams) {
        exportParams.getCondition().put("o.com_id", getComId());
        List<ExportOrderItemVO> list = service.getCMSViewModelListBySqlName("get_export_charge_order_page", ExportOrderItemVO.class,exportParams.getProperties(),
                exportParams.getValues(),exportParams.getRangeEntitys(),exportParams.getOrderNames(),exportParams.getSortOns(),
                new Object[]{exportParams.getStart(),exportParams.getLimit()});

        boolean isException = false;

        if(exportParams.getCondition().containsKey("o.is_exception") &&
                StringUtil.equals(exportParams.getCondition().get("o.is_exception"),YesOrNo.Yes.name())) {
            isException = true;
        }


        Map<String,String> mapStatus = getParam("order.order_status");
        Map<String,String> pbEndType = getParam("order.stopReason.PB");
        Map<String,String> ebEndType = getParam("order.stopReason.EB");
        Map<String,String> evEndType = getParam("order.stopReason.EV");
        Map<String,String> eboxEndType = getParam("order.stopReason.EBox");

        Map<String,String> pbException = getParam("order.exception.PB");
        Map<String,String> ebException = getParam("order.exception.EB");
        Map<String,String> evException = getParam("order.exception.EV");
        Map<String,String> eboxException = getParam("order.exception.EBox");

        list.stream().forEach(orderItem -> {
            orderItem.setOrderStatus(statusService.getOrderStatus(orderItem.getChargeOrderId(),orderItem.getStatus(),orderItem.getPayStatus(),orderItem.getDeviceType()));

            if(orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing){
                service.setOrderDurationAndAmount(orderItem);

                if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EB.name())){
                    EbOrder ebOrder = ebOrderService.getEntity("charge_order_id", orderItem.getChargeOrderId());
                    if(ebOrder != null) {
                        if (orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing && StringUtil.equals(ebOrder.getFeeType(), OrderEnum.FeeType.Energy.name())) {
                            ebOrder.setServiceFee(orderService.getServiceFee(orderItem.getChargeOrderId()));
                            ebOrder.setEnergyFee(orderService.getEnergyFee(orderItem.getChargeOrderId()));

                            orderItem.setChargeAmount(ebOrder.getServiceFee() + ebOrder.getEnergyFee());
                            orderItem.setOrderAmount(orderItem.getChargeAmount());
                        }

                        if(orderItem.getOrderStatus() == OrderEnum.OrderStatus.Doing){
                            ebOrder.setChargeCapacity(orderService.getCapacity(orderItem.getChargeOrderId()));
                        }
                    }
                }
            }

            orderItem.setAfterDiscountsAmount(orderItem.getOrderAmount() - orderItem.getCouponsAmount() - orderItem.getDiscountsAmount());

            if(OrderEnum.OrderStatus.Place == orderItem.getOrderStatus() && DeviceTypeEnum.EV.name().equals(orderItem.getDeviceType())){
                EvOrderVO evOrderVO = UMBeanUtils.copyBean(evOrderService.getEntity("charge_order_id",orderItem.getChargeOrderId()),EvOrderVO.class);
                service.calcEVOrderPlaceFee(orderItem,evOrderVO);
            }else if(OrderEnum.OrderStatus.Place == orderItem.getOrderStatus() && DeviceTypeEnum.EBox.name().equals(orderItem.getDeviceType())){
                EboxOrderVO eboxOrderVO = UMBeanUtils.copyBean(eboxOrderService.getEntity("charge_order_id",orderItem.getChargeOrderId()),EboxOrderVO.class);
                service.calcEBoxOrderPlaceFee(orderItem,eboxOrderVO);
            }

            // TODO 订单列表免费订单不显示订单金额，订单详情要显示，后面可能会改
            if(YesOrNo.Yes.name().equals(orderItem.getIsFree())){
                orderItem.setOrderAmount(0);
            }

            orderItem.setStationAddress(orderItem.getProvince()+orderItem.getCity()+orderItem.getArea()+orderItem.getAddress());
            orderItem.setChargeMin(orderItem.getDuration() / 60);
            orderItem.setChargeCapacity((int)(orderItem.getChargeCapacity() / 1000.0 * 100));// * 100为了按小数显示

            String status = mapStatus.get(orderItem.getStatus());
            if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name()) && StringUtil.equals(orderItem.getStatus(),OrderEnum.Status.Failure.name())){
                status = "出柜失败";
            }else if(!StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name()) && StringUtil.equals(orderItem.getStatus(),OrderEnum.Status.Failure.name())){
                status = "启动失败";
            }
            orderItem.setStatus(status);

            String endType = StringUtil.getTrim(orderItem.getEndType());
            if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name())){
                endType = pbEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EB.name())){
                endType = ebEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EV.name())){
                endType = evEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EBox.name())){
                endType = eboxEndType.get(endType);
            }
            orderItem.setEndType(StringUtil.getTrim(endType));

            String exception = StringUtil.getTrim(orderItem.getExceptionType());
            if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name())){
                exception = pbException.get(exception);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EB.name())){
                exception = ebException.get(exception);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EV.name())){
                exception = evException.get(exception);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EBox.name())){
                exception = eboxException.get(exception);
            }
            orderItem.setExceptionType(StringUtil.getTrim(exception));

        });

        Map mapFormat = new Hashtable();
        mapFormat.put("create_time","yyyy-MM-dd HH:mm:ss");

        mapFormat.put("energy_fee","number");
        mapFormat.put("service_fee","number");
        mapFormat.put("order_amount","number");
        mapFormat.put("coupons_amount","number");
        mapFormat.put("discounts_amount","number");
        mapFormat.put("after_discounts_amount","number");
        mapFormat.put("pay_amount","number");
        mapFormat.put("return_amount","number");
        mapFormat.put("charge_capacity","number");

        String fileName = "Excel"+ com.um.springboot.starter.utils.DateUtil.getDateString(new Date(), "yyyyMMddHHmmss")+".xls";
        String path = service.getExportFilePath(fileName);
        List<String> columns = Arrays.asList("订单编号","创建时间","商户订单号","订单类型","用户昵称","用户手机","运营商名称","运营商手机","站场名称","站场地址","设备名称","设备编号","端号",
                "充电时长(分钟)","充电电量(度)","充电电费","服务费","订单费用","优惠金额","满减金额","折后金额","支付金额","退回金额","支付方式","支付状态","充电状态","订单状态","结束类型",
                "尖电量(度)","峰电量(度)","平电量(度)","谷电量(度)");

        List<String> properties = Arrays.asList("order_no","create_time","out_trade_no","device_type","nickname","mobile","merchant_name","merchant_mobile","station_name","station_address","device_name","device_code","port",
                "charge_min","charge_capacity","energy_fee","service_fee","order_amount","coupons_amount","discounts_amount","after_discounts_amount","pay_amount","return_amount","pay_way","pay_status","status","order_status","end_type",
                "sharp_capacity","peak_capacity","shoulder_capacity","off_peak_capacity");

        if(isException) {
            columns = new ArrayList<>(columns);
            columns.add("异常状态");
            columns.add("异常描述");

            properties = new ArrayList<>(properties);
            properties.add("exception_status");
            properties.add("exception_type");
        }

        ExcelUtil.writeEntity(path, columns, list, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(),true);

        return Response.success(service.getDownFilePath(fileName));
    }

    private Map<String,String> getParam(String path){
        Map<String,String> map = new Hashtable<>();

        List<Param> allParam = paramService.getList (new String[]{"path","is_leaf"},new Object[]{path,"Yes"});
        for(Param param : allParam){
            map.put(param.getPKey(),param.getPValue());
        }

        return map;
    }


    public Response exportComplaintOrderPage(ExportParams exportParams) {
        exportParams.getCondition().put("o.com_id", getComId());
        List<ExportComplaintOrderItemVO> list = service.getCMSViewModelListBySqlName("get_charge_complaint_order_page", ExportComplaintOrderItemVO.class,exportParams.getProperties(),
                exportParams.getValues(),exportParams.getRangeEntitys(),exportParams.getOrderNames(),exportParams.getSortOns(),
                new Object[]{exportParams.getStart(),exportParams.getLimit()});




        Map<String,String> mapStatus = getParam("order.order_status");
        Map<String,String> pbEndType = getParam("order.stopReason.PB");
        Map<String,String> ebEndType = getParam("order.stopReason.EB");
        Map<String,String> evEndType = getParam("order.stopReason.EV");
        Map<String,String> eboxEndType = getParam("order.stopReason.EBox");

        list.stream().forEach(orderItem -> {

            orderItem.setStationAddress(orderItem.getProvince()+orderItem.getCity()+orderItem.getArea()+orderItem.getAddress());
            orderItem.setChargeMin(orderItem.getDuration() / 60);

            String status = mapStatus.get(orderItem.getStatus());
            if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name()) && StringUtil.equals(orderItem.getStatus(),OrderEnum.Status.Failure.name())){
                status = "出柜失败";
            }else if(!StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name()) && StringUtil.equals(orderItem.getStatus(),OrderEnum.Status.Failure.name())){
                status = "启动失败";
            }
            orderItem.setStatus(status);
            orderItem.setAfterDiscountsAmount(orderItem.getOrderAmount() - orderItem.getCouponsAmount() - orderItem.getDiscountsAmount());

            String endType = StringUtil.getTrim(orderItem.getEndType());
            if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.PB.name())){
                endType = pbEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EB.name())){
                endType = ebEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EV.name())){
                endType = evEndType.get(endType);
            }else if(StringUtil.equals(orderItem.getDeviceType(),DeviceTypeEnum.EBox.name())){
                endType = eboxEndType.get(endType);
            }
            orderItem.setEndType(StringUtil.getTrim(endType));

        });

        Map mapFormat = new Hashtable();
        mapFormat.put("create_time","yyyy-MM-dd HH:mm:ss");
        mapFormat.put("complaint_time","yyyy-MM-dd HH:mm:ss");

        mapFormat.put("energy_fee","number");
        mapFormat.put("service_fee","number");
        mapFormat.put("order_amount","number");
        mapFormat.put("coupons_amount","number");
        mapFormat.put("discounts_amount","number");
        mapFormat.put("after_discounts_amount","number");
        mapFormat.put("pay_amount","number");
        mapFormat.put("return_amount","number");
        mapFormat.put("charge_capacity","number");

        String fileName = "Excel"+ com.um.springboot.starter.utils.DateUtil.getDateString(new Date(), "yyyyMMddHHmmss")+".xls";
        String path = service.getExportFilePath(fileName);
        List<String> columns = Arrays.asList("订单编号","创建时间","商户订单号","订单类型","用户昵称","用户手机","投诉问题","用户问题描述","投诉时间","投诉状态","投诉处理人","运营商名称","运营商手机","站场名称","站场地址","设备名称","设备编号","端号",
                "充电时长(分钟)","充电电量(度)","充电电费","服务费","订单费用","优惠金额","满减金额","折后金额","支付金额","退回金额","支付方式","支付状态","充电状态","订单状态","结束类型");

        List<String> properties = Arrays.asList("order_no","create_time","out_trade_no","device_type","nickname","mobile","complaint_title","complaint_problem","complaint_time","complaint_status","hand_name","merchant_name","merchant_mobile","station_name","station_address","device_name","device_code","port",
                "charge_min","charge_capacity","energy_fee","service_fee","order_amount","coupons_amount","discounts_amount","after_discounts_amount","pay_amount","return_amount","pay_way","pay_status","status","order_status","end_type");


        ExcelUtil.writeEntity(path, columns, list, properties, exportParams.getMapParam(), mapFormat, exportParams.getMapZero(),true);

        return Response.success(service.getDownFilePath(fileName));
    }

    private void baofuRefund(String outRefundNo) {
        //查询明细数据
        List<BaofuAccountDetails> details = baofuAccountDetailsService.getRows(new String[]{"out_trade_no","account_type"}, new Object[]{outRefundNo,FinancialEnum.IncomeOrExpend.Income.name()});
        if(details!=null && details.size()>0){
            List<BaofuAccountDetails> addDetails =new ArrayList<>();
            ValuesActionEntity actionEntity = new ValuesActionEntity();
            List<ValuesAcctInfoEntity> acctInfo =  new ArrayList<>();
            ValuesAcctInfoEntity acctInfoEntity =  null;
            String transSerialNo =OrderUtil.getTxOrderNo();
            Integer dealAmount = 0;
            for(BaofuAccountDetails vo:details){
                acctInfoEntity = new ValuesAcctInfoEntity();
                acctInfoEntity.setContractNo(vo.getContractNo());
                acctInfoEntity.setTransAmount(new BigDecimal(vo.getCommission()).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                acctInfoEntity.setRemark("订单："+vo.getOutTradeNo()+"进行比退款");
                dealAmount = dealAmount + vo.getCommission();
                acctInfo.add(acctInfoEntity);
                //写人账户明细数据
                BaofuAccountDetails accountDetails = new BaofuAccountDetails();
                accountDetails.setCommissionId(vo.getCommissionId());
                accountDetails.setContractNo(vo.getContractNo());
                accountDetails.setCommission(vo.getCommission());
                accountDetails.setCommissionRate(vo.getCommissionRate());
                accountDetails.setChargeOrderId(vo.getChargeOrderId());
                accountDetails.setTransSerialNo(transSerialNo);
                accountDetails.setOutTradeNo(vo.getOutTradeNo());
                accountDetails.setOrderAmount(vo.getOrderAmount());
                accountDetails.setAccountType(FinancialEnum.IncomeOrExpend.Expend.name());
                accountDetails.setType(vo.getType());
                accountDetails.setCreateTime(new Date());
                //accountDetails.setBaofuAccountDetailsId(UUID.randomUUID().toString().replaceAll("-",""));
                addDetails.add(accountDetails);
            }
            actionEntity.setAcctInfo(acctInfo);
            actionEntity.setTransOrderNo("TSN"+ FormatUtil.CreateAeskey(20));
            actionEntity.setTransSerialNo(transSerialNo);
            actionEntity.setOrderNo(outRefundNo);
            actionEntity.setDealAmount(new BigDecimal(dealAmount).divide(BigDecimal.valueOf(100)).setScale(2, BigDecimal.ROUND_HALF_UP));
            ContentBodyEntity<RsultBodyEntity> contentBody = baoFuAccountService.BCT3_5002_001_01(actionEntity);
            if (contentBody.getBody().getState() == 1){
                //添加宝付流水
                if(addDetails!=null && addDetails.size()>0){
                    for(BaofuAccountDetails vo:addDetails){
                        baofuAccountDetailsService.saveRow(vo);
                    }
                }
            }
        }
    }
}
